package com.gamex.findit.controller.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gamex.findit.Constants;
import com.gamex.findit.model.Member;
import com.gamex.findit.service.MemberService;
import com.gamex.findit.util.CryptoUtil;

@Controller
public class LoginController {
	
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired MemberService memberService;
	
	/**
	 * @param session
	 * @param request
	 * @param response
	 * @param model
	 * @param member
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/admin/login")
	public String login(HttpSession session , HttpServletRequest request
			  		  , HttpServletResponse response , Model model
			          , @ModelAttribute Member member) throws Exception{
		
		List<Member> m = null;
		String password = CryptoUtil.getEncryptedPassword(member.getUserPass());
		member.setUserPass(password);
		try {
			m = memberService.getMember(member);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		
		if(m != null && m.size() == 1 ){
			String redirect = "";
			if(m.get(0).getUserRole().equals("ADMIN"))
				redirect = "redirect:/admin/imageList.json";
			else
				redirect = "redirect:/member/imageList.json";
				
			
			session.setAttribute(Constants.SESSION_INFO, m.get(0));
			return redirect;
			
		}else{
			session.invalidate();
			model.addAttribute("result","invalid id,password retry again");
			return "/login/login";
		}
		
	}
	
	/**
	 * @param session
	 * @param request
	 * @param response
	 * @param model
	 * @param member
	 * @throws Exception
	 */
	@RequestMapping("/admin/logout")
	public void logout(HttpSession session , HttpServletRequest request
			  		  , HttpServletResponse response , Model model
			          , @ModelAttribute Member member) throws Exception{
		
		session.invalidate();
		response.sendRedirect(request.getContextPath() +"/index.jsp");
	}
	
	
	
}
